<?php
/*
Plugin Name: Tinel's translation services marketplace
Plugin URI: http://www.linguisticguide.com
Description: This plugin realizes the implementation of a simple marketplace to sell translation services using an online site
Version: 1.0.0
Author: Constantin Bogza
Author URI: http://linguisticguide.com
License: GPLv2
*/

/*  Copyright 2012  Constantin Bogza  (email : constantinbogza@gmail.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
/* include dependant files */
require_once('includes/tb_trser_market_database.php');

// language activation
add_action( 'init', 'tb_trser_market_init_language' );

/* activation and deactivation */
register_activation_hook( __FILE__, 'tb_trser_market_install' );
register_deactivation_hook( __FILE__,'tb_trser_market_uninstall' );

/* header hooks */
/* css addon */
add_action( 'admin_init', 'tb_trser_market_css' );
add_action( 'init', 'tb_trser_market_css' );
/* js addons */
add_action( 'admin_init', 'tb_trser_market_js' );
add_action( 'init', 'tb_trser_market_js' );


/* administration menu */
add_action( 'admin_menu', 'tb_trser_market_create_menu',1 );
add_action( 'admin_init', 'tb_trser_market_admin_init' );

/* add upload posibility */
add_action( 'post_edit_form_tag', 'tb_trser_market_form_add_enctype' );

/* add footer action for the jquiry */
require_once('includes/tb_trser_market_footer.php');
add_action('admin_footer', 'tb_trser_market_admin_footer');
add_action('wp_footer', 'tb_trser_market_footer');


/* Shortcodes */
/* add shortcode for placing a translation */
add_shortcode( 'tb_trser_order', 'tb_trser_market_order_shortcode' );
/* add shortcode to show the current status of a translation */
add_shortcode( 'tb_trser_myorders', 'tb_trser_market_myorders_shortcode' );
/* add shortcode to show the new orders placed on the site */
add_shortcode( 'tb_trser_neworders', 'tb_trser_market_neworders_shortcode' );


/* site processing actions  - enables the processing of user actions */
add_action( 'template_redirect', 'tb_trser_market_template_redirect' );

function tb_trser_market_init_language() {
	load_plugin_textdomain( 'tb_trser_market',
							false,
							dirname( plugin_basename( __FILE__ ) )
							. '/languages' );
}

/* redirect funtion depinding on the form that was called */
function tb_trser_market_template_redirect( $template ) {	
	if ( !empty( $_POST['tb_trser_market_loginformstats'] ) ) {
		tb_trser_market_login_process();
	} else {
		return $template;
	}		
}

/* instalation hook for the marketplace plugin */
function tb_trser_market_install() {
	/* check compatibility for wordpress */
    if ( version_compare( get_bloginfo( 'version' ), '3.1', '<' ) ) {
        deactivate_plugins( basename( __FILE__ ) ); // Deactivate our plugin */
    }
	/* install the plugin options if they do not already exist */
	if ( get_option( 'tb_trser_market_options' ) === false ) {
		$new_options['tb_trser_market_shipping_address'] = "Romania";
		$new_options['tb_trser_market_company_name'] = "Your Company Name";
		$new_options['tb_trser_market_version'] = "1.1";
		add_option( 'tb_trser_market_options', $new_options );
	} else {
		$existing_options = get_option( 'tb_trser_market_options' );
		/* check for the option version and replace them if they are too old */
		if ( $existing_options['tb_trser_market_version'] < 1.1 ) {
			$new_options['tb_trser_market_shipping_address'] = "Romania";
			$existing_options['version'] = "1.1";
			$new_options['tb_trser_market_version'] = "1.1";
			update_option( 'tb_trser_market_version', $existing_options );
		}
	}
	/* Get access to global database access class */
        require_once('includes/tb_trser_market_database.php');
        tb_trser_market_create_database();
}

function tb_trser_market_uninstall() {
/* deactivation hook */
}

/* css snippit */
function tb_trser_market_css() {
wp_enqueue_style( 'tbtranslationservicesmarketplace', plugins_url( "css/tb_trser_market.css", __FILE__ ), array(), '20121209' );
wp_enqueue_style( 'tbtranslationservicesmarketplaceui', plugins_url( "css/jquery-ui-1.9.1.custom.min.css", __FILE__ ), array(), '20121209' );
}
/* jquiry snippet */
function tb_trser_market_js() {
wp_enqueue_script( 'tbtranslationservicesmarketplace', plugins_url( "js/tb_trser_javascript.js", __FILE__ ));
wp_enqueue_script( 'tbtranslationservicesmarketplacejq', plugins_url( "js/jquery-1.8.3.min.js", __FILE__ ) );
wp_enqueue_script( 'tbtranslationservicesmarketplaceui', plugins_url( "js/jquery-ui-1.9.1.custom.min.js", __FILE__ ) );
}
/* administration menu */
function tb_trser_market_create_menu() {

	//create custom top-level menu
	add_menu_page( __('Translation Services Market Settings Page','tb_trser_market'), __('Translations','tb_trser_market'), 'read', __FILE__, 'tb_trser_market_settings_page', plugins_url( '/images/wp-icon.png', __FILE__ ) );
	
	//create submenu items
	add_submenu_page( __FILE__, __('About Translation Services Market','tb_trser_market'), __('All translations','tb_trser_market'), 'manage_options', __FILE__.'_about', tb_trser_market_all_translations_page );
	add_submenu_page( __FILE__, __('Help on Translation Services Market','tb_trser_market'), __('New translations','tb_trser_market'), 'manage_options', __FILE__.'_help', tb_trser_market_new_translations_page );
	add_submenu_page( __FILE__, __('Uninstall Translation Services Market','tb_trser_market'), __('Uninstall','tb_trser_market'), 'manage_options', __FILE__.'_uninstall', tb_trser_market_uninstall_page ); 

}

/* Translations backend page */
/* all translations page */
function tb_trser_market_all_translations_page(){
	$orders_array = tb_trser_market_get_all_orders();
	tb_trser_market_print_orders_table($orders_array,1);
}	

function tb_trser_market_new_translations_page(){
	$orders_array = tb_trser_market_get_new_orders();
	tb_trser_market_print_orders_table($orders_array,1);
}	
/* primary page for all users */
function tb_trser_market_settings_page() {
global $tb_trser_market_message;	
$options = tb_trser_market_get_user_options();
?>
<div id="tb_trser_market_general" class="wrap">
	<h2><?php _e("Translation dashboard","tb_trser_market"); ?></h2>
    <?php if ( isset( $_GET['message'] ) ) { ?>
				<div id='message' class='updated fade'><p><strong>  <?php echo tb_trser_market_transfer_message(false); ?> </strong></p></div>
	<?php } ?>
    <h1><?php _e("Hello ","tb_trser_market"); ?><?php echo esc_html( $options['tb_trser_market_name'] ); ?>!</h1>
    <div class="welcome-panel-column">
    <h4 id="tb_trser_mydetails"><span class="icon16 icon-page" /></h4><h4><?php _e('My account details','tb_trser_market'); ?> <a href="javascript:tb_trser_market_changedetails()"><?php _e('Change','tb_trser_market'); ?></a></h4>
	   <p>
       		<b><?php _e("Address: ","tb_trser_market"); ?></b>
            <span><?php echo esc_html( $options['tb_trser_market_address_name'] ); ?></span>
       </p>
       <p>
       		<b><?php _e("Shipping address: ","tb_trser_market"); ?> </b>
            <span><?php echo esc_html( $options['tb_trser_market_shipping_address'] ); ?></span>
       </p>
       <p>
       		<b><?php _e("Company name: ","tb_trser_market");?></b>
            <span><?php echo esc_html( $options['tb_trser_market_company_name'] ); ?></span>
       </p>
       <p>
       		<b><?php _e("Country: ","tb_trser_market");?></b>
            <span><?php echo esc_html( $options['tb_trser_market_country'] ); ?></span>
       </p>
       <p>
       		<b><?php _e("Tax Identification Code: ","tb_trser_market"); ?></b>
            <span><?php echo esc_html( $options['tb_trser_market_tax_identification_code'] ); ?></span>
       </p>
    </div>
    <div class="postbox " id="tb_trser_market_invoice_details">
        <h3 class="hndle"><?php _e('Change my account details','tb_trser_market'); ?></h3>
        <form method="post" action="<?php echo admin_url();?>/admin-post.php">
            <input type="hidden" name="action" value="save_tb_trser_market_options" />
            <!-- Adding security through hidden referrer field -->
            <?php wp_nonce_field( 'tb_trser_market' ); ?>
            <table class="inside" id="invoice_details_table">
            <tr>
                <td id="first_column"> <?php _e("Shipping address: ","tb_trser_market"); ?> </td>
                <td id="second_column"> <textarea class="textarea-wrap" name="tb_trser_market_shipping_address"><?php echo esc_html( $options['tb_trser_market_shipping_address'] ); ?></textarea></td>
            </tr>
            <tr>
                <td> <?php _e("Company name: ","tb_trser_market"); ?> </td>
                <td> <input class="input-text-wrap" type="text" name="tb_trser_market_company_name" value="<?php echo esc_html( $options['tb_trser_market_company_name'] ); ?>"/></td>
            </tr>
            <tr>
                <td> <?php _e("Name (contact person for invoice payment): ","tb_trser_market"); ?></td>
                <td><input class="input-text-wrap" type="text" name="tb_trser_market_name" value="<?php echo esc_html( $options['tb_trser_market_name'] ); ?>"/></td>
            </tr>
            <tr>
                <td><?php _e("Address: ","tb_trser_market"); ?> </td>
                <td><textarea class="textarea-wrap" name="tb_trser_market_address_name"><?php echo esc_html( $options['tb_trser_market_address_name'] ); ?></textarea></td>
            </tr>
            <tr>
                <td><?php _e("Country: ","tb_trser_market"); ?></td>
                <td><input class="input-text-wrap" type="text" name="tb_trser_market_country" value="<?php echo esc_html( $options['tb_trser_market_country'] ); ?>"/></td>
            </tr>
            <tr>
                <td><?php _e("Tax Identification Code: ","tb_trser_market"); ?></td>
                <td> <input class="input-text-wrap" type="text" name="tb_trser_market_tax_identification_code" value="<?php echo esc_html( $options['tb_trser_market_tax_identification_code'] ); ?>"/></td>
            </tr>
            </table>
            <input type="submit" value="<?php _e("Update invoice details","tb_trser_market"); ?>" class="button-primary"/>
        </form>
    </div>
<div>

<?php 
if(current_user_can('manage_options')){
	$orders_array = tb_trser_market_get_all_orders();
	tb_trser_market_print_orders_table($orders_array,1);
}
/* print also the table containing the user orders */
$orders_array = tb_trser_market_get_user_orders();
tb_trser_market_print_orders_table($orders_array,1);
}

/* html output to upload a file for a new order */
function tb_trser_market_print_upload_file_new_order(){

$html = "<form method=\"post\" action=\"".admin_url()."admin-post.php\" enctype=\"multipart/form-data\">";
$html .="<input type=\"hidden\" name=\"action\" value=\"save_tb_trser_order_request\" />";
$html .= wp_nonce_field( 'tb_trser_market' );
$html .="<label for=\"file\">".__('Place a translation order: ','tb_trser_market')."</label>";
$html .="<input type=\"file\" name=\"tb_trser_file\" id=\"tb_trser_file\" /> ";
$html.= "<div id=\"tb_trser_market_layout_div\"><span>".__('Layout: ','tb_trser_market')."</span>";
$html.= "<input type=\"radio\" name=\"tb_trser_market_importance\" id=\"tb_trser_market_layout\" value=\"very important\" checked=\"true\" /><label class=\"meta\">".__('Very important','tb_trser_market')."</label>";
$html.= "<input type=\"radio\" name=\"tb_trser_market_importance\" id=\"tb_trser_market_layout\" value=\"less important\" /><label class=\"meta\">".__('Less important','tb_trser_market')."</label>";
$html.= "<input type=\"radio\" name=\"tb_trser_market_importance\" id=\"tb_trser_market_layout\" value=\"not important\" /><label class=\"meta\">".__('Not important','tb_trser_market')."</label>";
$html.="</div>";
$html .="<input type=\"submit\" value=\"".__('Order','tb_trser_market')."\" class=\"button-primary\"/>";
$html .="</form>";
return $html;
}

/* printout current logged in user */
function tb_trser_market_print_orders_table($tb_trser_market_orders,$admin){
	// $admin tells if the request comes from a admin page or a webpage
	require_once('includes/tb_trser_market_new_account.php');
	echo tb_trser_market_new_user_print_message();
?>
<div id="tb_trser_market_general" class="wrap">
	<div class="postbox ">
        <h3 class="hndle"><?php _e('My translations','tb_trser_market'); ?></h3>
        <?php if($admin == 0) {echo tb_trser_market_order_shortcode();} else { echo tb_trser_market_print_upload_file_new_order();}?>
        <table class="widefat" <?php if ( !is_user_logged_in()) {echo "id='hidden'";} else {echo "id='tb_trser_market_order_tb'";}?>>
            <thead>
                <tr>
                	<th id="tb_trser_market_order_tb_id"><?php _e('No','tb_trser_market'); ?></th>
                	<th id="tb_trser_market_order_tb_status"><?php _e('Status','tb_trser_market'); ?></th>
                   	<th id="tb_trser_market_order_tb_file"><?php _e('File','tb_trser_market'); ?></th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                	<th><?php _e('No','tb_trser_market'); ?></th>                
                	<th><?php _e('Status','tb_trser_market'); ?></th>
                   	<th><?php _e('File','tb_trser_market'); ?></th>
                </tr>
            </tfoot>
            <tbody>
<? 
	if(isset($tb_trser_market_orders))
	{
		$iCnt = 1;
		foreach ( $tb_trser_market_orders as $order ) {
	          echo "<tr>";
 	          echo "<td id='tb_trser_market_orders_no'>".$iCnt."</td>";
   	          echo "<td><table><tr><td>".__('Current status: ','tb_trser_market')."</td><td>".__($order['tb_trser_market_status'],'tb_trser_market')."</td></tr>";
  			  echo "<tr><td>".__('Estimated date: ','tb_trser_market')."</td><td>";
			  if(isset($order['tb_trser_market_estimated_due_date'])&&strlen($order['tb_trser_market_estimated_due_date']>0)){
			  echo $order['tb_trser_market_estimated_due_date'];
			  echo   " ".__(' business day(s) from transmission of purchase order.','tb_trser_market');
			  }else {
			  }
			  echo "</td></tr>";
	          echo "<tr><td>".__('Uploaded: ','tb_trser_market')."</td><td>".substr($order['tb_trser_market_upload_date'],0,10)."</td></tr>";
			  echo "<tr><td>".__('Accepted: ','tb_trser_market')."</td><td>".substr($order['tb_trser_market_accepted_date'],0,10)."</td></tr>";
			  echo "<tr><td>".__('Finished: ','tb_trser_market')."</td><td>".substr($order['tb_trser_market_finished_date'],0,10)."</td></tr>";
			  echo "</table></td>";
			  echo "<td><table><tr><td id='tb_trser_market_file_name'>".__('File name: ','tb_trser_market')."</td><td>".$order['tb_trser_market_document_name']."</td></tr>";
  			  echo "<tr><td>".__('Layout importance: ','tb_trser_market')."</td><td>".__($order['tb_trser_market_importance'],'tb_trser_market')."</td></tr>";
			  echo "<tr><td>".__('Download file: ','tb_trser_market')."</td><td><a href='".$order['tb_trser_market_document_link']."'><img src='".plugins_url( 'images/initial_file.png', __FILE__ )."' align='middle' alt='".$order['tb_trser_market_document_name']."'  id='tb_trser_market_initial_img'> </a></td></tr>";
			  echo "<tr><td>".__('Download translation: ','tb_trser_market')."</td>";
			  if(strlen($order['tb_trser_market_translation_link']) > 10)
			  {
			  	echo "<td><a href='".$order['tb_trser_market_translation_link']."'><img src='".plugins_url( 'images/translated_file.png', __FILE__ )."' align='middle' alt='".$order['tb_trser_market_document_name']."' id='tb_trser_market_translation_img'> </a></td></tr>";
			  }
			  else
			  {
				echo "<td>".__('not available','tb_trser_market')."</td></tr>";
			  }
			  echo "<tr><td><b>".__('Price: ','tb_trser_market')."</b></td><td><b>".__($order['tb_trser_market_price'],'tb_trser_market')." &euro;</b></td></tr>";
  			  echo "<tr><td>".__('Action: ','tb_trser_market')."</td><td>".tb_trser_market_print_buttons($order)."</td></tr></table>";
  			  echo "</td></tr>";
			  $iCnt = $iCnt + 1;
		}
	}
?>
            </tbody>
        </table>
	</div>
</div>
<?php

}

/* print  functions for the order tables */
function tb_trser_market_print_buttons($tb_trser_market_order) {
	$order_id = $tb_trser_market_order['tb_trser_market_order_id'];
	if(current_user_can('manage_options')){
		$html = "<form method=\"post\" action=\"".admin_url()."admin-post.php\" enctype=\"multipart/form-data\">";
		$html .= "<input type=\"hidden\" name=\"action\" value=\"save_tb_trser_order_update\" />";
		$html .= wp_nonce_field( 'tb_trser_market' );
		// make correct transitions new -> quoted -> accepted -> in translation -> finished
		if(strcmp($tb_trser_market_order['tb_trser_market_status'],"new")==0){
			$html .= "<input type=\"submit\" value=\"Quote\" class=\"button-primary\"/>";
			$html .= "<input type=\"text\" name=\"tb_trser_market_due_date\" id=\"tb_trser_market_due_date_".$order_id."\" placeholder=\"Working days\" size=\"15\" />";
			$html .= "<input type=\"text\" name=\"tb_trser_market_price\" id=\"tb_trser_market_price\" placeholder=\"Price\" size=\"15\" />";
			$html .= "<input  type=\"hidden\" name=\"tb_trser_market_order_id\" id=\"tb_trser_market_order_id\" placeholder=\"Price\" size=\"15\" value=\"".$order_id."\"/>";
		}
		if(strcmp($tb_trser_market_order['tb_trser_market_status'],"quoted")==0){
			if(tb_trser_market_check_is_user_order($tb_trser_market_order))
			{
				$html .= __('By clicking accept you will also be able to send us the purchase order','tb_trser_market').".</br>";
				$html .= "<input type=\"submit\" value=\"".__('Accept','tb_trser_market')."\" class=\"button-primary\" name=\"tb_trser_market_order_decision\"/>";
				$html .= "<input type=\"submit\" value=\"".__('Cancel','tb_trser_market')."\" class=\"button-primary\" name=\"tb_trser_market_order_decision\"/>";
				$html .= "<input  type=\"hidden\" name=\"tb_trser_market_order_id\" id=\"tb_trser_market_order_id\" placeholder=\"Price\" size=\"15\" value=\"".$order_id."\"/>";

			}
			else
			{
				$html .= "<input type=\"submit\" value=\"".__('Accept','tb_trser_market')."\" class=\"button-primary\" disabled=\"disabled\" name=\"tb_trser_market_order_decision\"/>";
				$html .= "<input type=\"submit\" value=\"".__('Cancel','tb_trser_market')."\" class=\"button-primary\" disabled=\"disabled\" name=\"tb_trser_market_order_decision\"/>";
			}
		}
		if(strcmp($tb_trser_market_order['tb_trser_market_status'],"accepted")==0){
				$html .= "<input type=\"submit\" value=\"Start\" class=\"button-primary\"/>";
				$html .= "<input  type=\"hidden\" name=\"tb_trser_market_order_id\" id=\"tb_trser_market_order_id\" placeholder=\"Price\" size=\"15\" value=\"".$order_id."\"/>";

		}
		if(strcmp($tb_trser_market_order['tb_trser_market_status'],"in translation")==0){
			$html .= "<input type=\"submit\" value=\"Finish\" class=\"button-primary\"/>";
			$html .= "<input  type=\"hidden\" name=\"tb_trser_market_order_id\" id=\"tb_trser_market_order_id\" placeholder=\"Price\" size=\"15\" value=\"".$order_id."\"/>";
			$html .="<input type=\"file\" name=\"tb_trser_file\" id=\"tb_trser_file\" placeholder=\"Translation\" size=\"15\"/> ";
		}
		$html .= "</form>";
	}else{
		$html = "<form method=\"post\" action=\"".admin_url()."admin-post.php\">";
		$html .= "<input type=\"hidden\" name=\"action\" value=\"save_tb_trser_order_update\" />";
		$html .= wp_nonce_field( 'tb_trser_market' );
		if(strcmp($tb_trser_market_order['tb_trser_market_status'],"quoted")==0){
			$html .= __('By clicking accept you will also be able to send us the purchase order.','tb_trser_market')."</br>";
			$html .= "<input type=\"submit\" value=\"".__('Accept','tb_trser_market')."\" class=\"button-primary\" name=\"tb_trser_market_order_decision\"/>";
			$html .= "<input type=\"submit\" value=\"".__('Cancel','tb_trser_market')."\" class=\"button-primary\" name=\"tb_trser_market_order_decision\"/>";
			$html .= "<input  type=\"hidden\" name=\"tb_trser_market_order_id\" id=\"tb_trser_market_order_id\" placeholder=\"Price\" size=\"15\" value=\"".$order_id."\"/>";

		}else{
			if(strcmp($tb_trser_market_order['tb_trser_market_status'],"new")==0) {
				$html .= "<input type=\"submit\" value=\"".__('Under quotation','tb_trser_market')."\" class=\"button-primary\"  disabled=\"disabled\"/>";
			}else{
				if(strcmp($tb_trser_market_order['tb_trser_market_status'],"canceled")==0) {
					$html .= "<input type=\"submit\" value=\"".__('Canceled','tb_trser_market')."\" class=\"button-primary\"  disabled=\"disabled\"/>";
				}
				else
				{
					$html .= "<input type=\"submit\" value=\"".__('Ordered','tb_trser_market')."\" class=\"button-primary\"  disabled=\"disabled\"/>";
				}
			}
		}
		$html .= "</form>";
	}
	return $html;
}

/* functions for processing order updates */
function process_tb_trser_market_order_update(){
if ( !is_user_logged_in()) wp_die( __('Not allowed to do order updates if you are not logged in!','tb_trser_market') );
/* Check that once field created in configuration form is present */
if(!check_admin_referer( 'tb_trser_market' )) wp_die( __('Not allowed to do order updates if you do not execute code from the site!','tb_trser_market') );
$message = __('Order table updated!','tb_trser_market')."<br />";
$message .= __('Update id: ','tb_trser_market').$_POST["tb_trser_market_order_id"]."<br />";
if(isset( $_POST["tb_trser_market_order_id"]))
{
	$order = tb_trser_market_get_order_id($_POST["tb_trser_market_order_id"]);
	$message .= $order['tb_trser_market_status'];
	if(strcmp($order['tb_trser_market_status'],"new")==0){
		if(isset( $_POST["tb_trser_market_order_id"])&&(is_numeric( $_POST["tb_trser_market_due_date"])==true)&&is_numeric( $_POST["tb_trser_market_price"]))
		{
		$message .= __('Updated due date: ','tb_trser_market').$_POST["tb_trser_market_due_date"]."<br />";
		$message .= __('Updated price: ','tb_trser_market').$_POST["tb_trser_market_price"]."<br />";
		$tb_trser_market_order = array( 'tb_trser_market_price' => $_POST["tb_trser_market_price"],
										'tb_trser_market_order_id' => $_POST["tb_trser_market_order_id"],
										'tb_trser_market_due_date' => $_POST["tb_trser_market_due_date"]);
		tb_trser_market_quote_user_order($tb_trser_market_order);
		/* send mail that the quote has been done */
		// include the location of the mail text
		require_once('includes/tb_trser_market_notification_emails.php');
		// place the mail text
		$tb_trser_market_customer_mail = tb_trser_market_customer_mail_file_quoted();
		wp_mail(tb_trser_market_get_user_email($_POST["tb_trser_market_order_id"]), __('[Linguistic guide] Your file has been quoted','tb_trser_market'), $tb_trser_market_customer_mail);
		$tb_trser_market_customer_mail .="\n Sent to: ".tb_trser_market_get_user_email($_POST["tb_trser_market_order_id"]);
		wp_mail('contact@linguisticguide.com', '[Linguistic guide] A file has been quoted', $tb_trser_market_customer_mail);
		}else{
			$message = __('You do not have all the fields updated!','tb_trser_market')."<br />";
			$message .= __('Update id: ','tb_trser_market').$_POST["tb_trser_market_order_id"]."<br />";
			if(tb_trser_market_valid_date( $_POST["tb_trser_market_due_date"])==false) $message .= __('Updated due date: ','tb_trser_market').$_POST["tb_trser_market_due_date"]."<br />";
			if(!is_numeric( $_POST["tb_trser_market_price"])) $message .= __('Update the price: ','tb_trser_market').$_POST["tb_trser_market_price"]."<br />";
		}
	
	}
	if(strcmp($order['tb_trser_market_status'],"quoted")==0){
		/* transition to accepted user can accept or deny the quote */
		if($_POST["tb_trser_market_order_decision"] == __('Accept','tb_trser_market')) {
			$message = __('Order has been accepted!','tb_trser_market')."<br />";
			$tb_trser_market_order = array( 'tb_trser_market_order_id' => $_POST["tb_trser_market_order_id"]);
			tb_trser_market_accept_user_order($tb_trser_market_order);
			wp_mail('contact@linguisticguide.com', '[Linguistic guide] A new file has been accepted', "The file with index: ".$_POST["tb_trser_market_order_id"]." has been accepted");
		}
		else
		{
			$message = __('Order has been canceled!','tb_trser_market')."<br />";
			$tb_trser_market_order = array( 'tb_trser_market_order_id' => $_POST["tb_trser_market_order_id"]);
			tb_trser_market_cancel_user_order($tb_trser_market_order);
			wp_mail('contact@linguisticguide.com', '[Linguistic guide] A new file has been canceled', "The file with index: ".$_POST["tb_trser_market_order_id"]." has been canceled");

		}
	}
	if(strcmp($order['tb_trser_market_status'],"accepted")==0){
		$message = __('Order has been started!','tb_trser_market')."<br />";
		$tb_trser_market_order = array( 'tb_trser_market_order_id' => $_POST["tb_trser_market_order_id"]);
		tb_trser_market_start_user_order($tb_trser_market_order);
	}
	if(strcmp($order['tb_trser_market_status'],"in translation")==0){
		$message = __('Order has been finished!','tb_trser_market')."<br />";
		$tb_trser_market_order = array( 'tb_trser_market_order_id' => $_POST["tb_trser_market_order_id"]);
		process_tb_trser_market_order_request();
	}
}
else
{
	$message = __('Order id does not exist!','tb_trser_market')."<br />";
}
tb_trser_market_transfer_message($message);
wp_redirect( add_query_arg( array('page' => 'tbtranslationservicesmarketplace/tbtranslationservicesmarketplace.php',
								  'message' => '1'),
								  admin_url( 'admin.php' ) ) ); 
}

/* function to show the status of my orders that were placed on the site */
function tb_trser_market_myorders_shortcode(){
/* print also the table containing the user orders */
$orders_array = tb_trser_market_get_user_orders();
tb_trser_market_print_orders_table($orders_array,0);
}

/* function to show the status of all the new the orders that were placed on the site */
function tb_trser_market_neworders_shortcode(){
// print also the table containing the user orders 
$orders_array = tb_trser_market_get_new_orders();
tb_trser_market_print_orders_table($orders_array,0);
}


/* function to process the shortcode for ordering translations */
function tb_trser_market_order_shortcode(){
	require_once('includes/recaptchalib.php');
	// Get a key from https://www.google.com/recaptcha/admin/create
	$publickey = "6Le_htkSAAAAADtdyJQEbaY4ZLqxcSa6cLxJ1I9O";
	$privatekey = "6Le_htkSAAAAAFK0HSZhF8SA4EKhy4IvglVb1H-O";
	/* user login */
	/* file selection section */
	$html = "<form method=\"post\" id=\"tb_trser_market_loginform\" action=\"\" enctype=\"multipart/form-data\">";	
	if ( !is_user_logged_in() )
	{
	/*ask for user details */
		$html.=	"<div id=\"tb_trser_user_login\"><input type=\"text\" name=\"tb_trser_market_user_name\" id=\"tb_trser_market_user_name\" placeholder=\"".__('User Name','tb_trser_market')."\" size=\"30\" />
				<input type=\"password\" name=\"tb_trser_market_password\" id=\"tb_trser_market_password\" placeholder=\"".__('Password','tb_trser_market')."\" size=\"30\" onclick=\"tb_trser_market_new_user_function()\" />
				<input type=\"checkbox\" name=\"tb_trser_market_new_user\" id=\"tb_trser_market_new_user\" onclick=\"tb_trser_market_new_user_function()\" />
				<label class=\"meta\">".__('I am a new user','tb_trser_market')."</label>";
		$html.=	"<input type=\"text\" name=\"tb_trser_market_email\" id=\"tb_trser_market_email\" placeholder=\"".__('Email','tb_trser_market')."\" size=\"30\" /></div>
				<div id=\"tb_trser_user_captcha\">";
		$html.=recaptcha_get_html($publickey, $error);
		$html.="</div>";
	}
	else
	{
		$html.= "<label for=\"file\">".__('Place a translation order: ','tb_trser_market')."</label>
			<input type=\"file\" name=\"tb_trser_file\" id=\"tb_trser_file\"/>";
	}
	// add nunance field to check the provenience of the user 
	$html.= wp_nonce_field( 'tb_trser_market' );
	$html.="<input type=\"hidden\" name=\"tb_trser_market_loginformstats\" value=\"1\" />";
	if ( !is_user_logged_in() ) {
		$html.= "<br/> <input type=\"submit\" value=\"".__('Step 1: Login or create an account','tb_trser_market')."\" class=\"button-primary\"/> <br/></form>";
	}
	else {
		$html.= "<div id=\"tb_trser_market_layout_div\"><span>".__('Layout: How important is it for you to keep the initial layout? ','tb_trser_market')."</span>";
		$html.= "<input type=\"radio\" name=\"tb_trser_market_importance\" id=\"tb_trser_market_layout\" value=\"very important\" checked=\"true\" /><label class=\"meta\">".__('Very important','tb_trser_market')."</label>";
		$html.= "<input type=\"radio\" name=\"tb_trser_market_importance\" id=\"tb_trser_market_layout\" value=\"less important\" /><label class=\"meta\">".__('Less important','tb_trser_market')."</label>";
		$html.= "<input type=\"radio\" name=\"tb_trser_market_importance\" id=\"tb_trser_market_layout\" value=\"not important\" /><label class=\"meta\">".__('Not important','tb_trser_market')."</label>";
		$html.="</div>";
		$html.= "<input type=\"submit\" value=\"".__('Step 2: Submit file for estimation','tb_trser_market')."\" class=\"button-primary\"/> <br/></form>";
	}
	return $html;
}

/* process the front order code */
function tb_trser_market_login_process(){
	/* check if the call is from a valid user */
	if ( !check_admin_referer( 'tb_trser_market' )){
		$abortmessage = __('Only submission from the site are allowed. Please use the site form! ','tb_trser_market');
		wp_die(	$abortmessage );
		exit;
	}
	require_once('includes/recaptchalib.php');
	
	// Get a key from https://www.google.com/recaptcha/admin/create
	$publickey = "6Le_htkSAAAAADtdyJQEbaY4ZLqxcSa6cLxJ1I9O";
	$privatekey = "6Le_htkSAAAAAFK0HSZhF8SA4EKhy4IvglVb1H-O";
	
	# the response from reCAPTCHA
	$resp = null;
	# the error code from reCAPTCHA, if any
	$error = null;
	
	# was there a reCAPTCHA response?
	if ( is_user_logged_in() ){
		process_tb_trser_market_order_request();
	}
	else{
		if($_POST["tb_trser_market_new_user"] != 'on'){
			tb_trser_market_user_process_login();
		}
		else{
			if ($_POST["recaptcha_response_field"]) {
					$resp = recaptcha_check_answer ($privatekey,
													$_SERVER["REMOTE_ADDR"],
													$_POST["recaptcha_challenge_field"],
													$_POST["recaptcha_response_field"]);
			
					if ($resp->is_valid) {
							/* everything is ok let's process the data create a new user or new account*/
							require_once('includes/tb_trser_market_new_account.php');
							tb_trser_market_new_user_creation(); //<- user is logged in
							/* now process the request of uploading the file */
							wp_redirect( site_url().__('/my-orders/','tb_trser_market'));
							exit; 
					} else {
							# set the error code so that we can display it
							$error = $resp->error;
							wp_die( __('Incorrect captcha! Please return to the previous page and try the captcha code again!','tb_trser_market'));
							exit;
					}
			}
			else
			{
				wp_die( __('Malformed input please send a mail to the server admin!','tb_trser_market'));
				exit;
			}
		}
	}
}

//login an existin account
function tb_trser_market_user_process_login(){
	// create a new user 
	$user_name = sanitize_user( $_POST["tb_trser_market_user_name"], true );
	$user_id = username_exists( $user_name );
	if ( !$user_id) {
		wp_die( __('User name or password incorrect!','tb_trser_market'));
		exit;
	}
	$creds = array();
	$creds['user_login'] = $user_name;
	$creds['user_password'] = sanitize_text_field($_POST["tb_trser_market_password"]);
	$creds['remember'] = true;
	$user = wp_signon( $creds, false );
	if ( is_wp_error($user) ){
		wp_die( __('Logon failed!Contact an admin.','tb_trser_market').$user->get_error_message());
		exit;

	}
	else
	{
		// redirect the user on the homepage
		wp_redirect( site_url().__('/my-orders/','tb_trser_market'));
	}
}

/* Translations backend page update action */
function tb_trser_market_admin_init() {
	add_action( 'admin_post_save_tb_trser_market_options', 'process_tb_trser_market_options');
	add_action( 'admin_post_save_tb_trser_order_request', 'process_tb_trser_market_order_request');
	add_action( 'admin_post_save_tb_trser_order_update', 'process_tb_trser_market_order_update');
}

/* Process the data sent from the main backend page */
function process_tb_trser_market_options() {
global $tb_trser_market_message;	
/* Check that user has proper security level */

if ( !is_user_logged_in() ) wp_die( __('Not allowed! You are not logged in.','tb_trser_market') );

/* Check that nonce field created in configuration form is present */
if ( !check_admin_referer( 'tb_trser_market' )){
		$abortmessage = __('Only submission from the site are allowed. Please use the site form! ','tb_trser_market');
		wp_die(	$abortmessage );
		exit;
	}
//check_admin_referer( 'tb_trser_market' );
/* Retrieve original plugin options array */
$options = tb_trser_market_get_user_options( 'tb_trser_market_options' );

/* Cycle through all text form fields and store their values in the options array */
foreach ( array( 'tb_trser_market_shipping_address','tb_trser_market_company_name','tb_trser_market_name','tb_trser_market_address_name','tb_trser_market_country','tb_trser_market_tax_identification_code') as $option_name ) {
	if ( isset( $_POST[$option_name] ) ) {
		$options[$option_name] =
		sanitize_text_field( $_POST[$option_name] );
	}
}
// Store updated options array to database
tb_trser_market_set_user_options( $options );
// Redirect the page to the configuration form that was
// processed
tb_trser_market_transfer_message( __('Options saved!','tb_trser_market'));
wp_redirect( add_query_arg( array('page' => 'tbtranslationservicesmarketplace/tbtranslationservicesmarketplace.php',
								  'message' => '1'),
								  admin_url( 'admin.php' ) ) );
exit;
}

/* Process the data sent from the main backend page for the orders */
/* add the posibility to upload */
function tb_trser_market_form_add_enctype() {
echo ' enctype="multipart/form-data"';
}
/* process the upload */
function process_tb_trser_market_order_request() {
/* Check that user has proper security level */
//if ( !current_user_can( 'manage_options' ) ) wp_die( 'Not allowed' );
if ( !is_user_logged_in() )wp_die( __('Not allowed! You are not logged in.','tb_trser_market') );

/* Check that once field created in configuration form is present */
if(!check_admin_referer( 'tb_trser_market' )) wp_die( __('Only submission from the site are allowed. Please use the site form! ','tb_trser_market') );
/* Retrieve original plugin options array */
$options = tb_trser_market_get_user_options( 'tb_trser_market_options' );
$allowedExts = array("doc", "docx", "pdf", "xls","zip","rar","xlsx");
$extension = end(explode(".", $_FILES["tb_trser_file"]["name"]));
$tb_trser_market_message = "";//Your file with the size: ".print_r($_FILES["tb_trser_file"],true). "<br />";
if (($_FILES["tb_trser_file"]["size"] < 20000000)
	&& in_array($extension, $allowedExts)) 
{
	if ($_FILES["tb_trser_file"]["error"] > 0)	{
		$tb_trser_market_message .= __('Return Code: ','tb_trser_market') . $_FILES["tb_trser_file"]["error"] . "<br />";
		$tb_trser_market_mail = "Return Code: " . $_FILES["tb_trser_file"]["error"] . "\n";
	}
	else{
		$tb_trser_market_message .= __('Upload: ','tb_trser_market') . $_FILES["tb_trser_file"]["name"] . "<br />";
		$tb_trser_market_mail = "Upload: " . $_FILES["tb_trser_file"]["name"] . "\n";
		$tb_trser_market_message .= __('Type: ','tb_trser_market') . $_FILES["tb_trser_file"]["type"] . "<br />";
		$tb_trser_market_mail .= __('Type: ','tb_trser_market') . $_FILES["tb_trser_file"]["type"] . "\n";
		$tb_trser_market_message .= __('Size: ','tb_trser_market') . ($_FILES["tb_trser_file"]["size"] / 1024) . " Kb<br />";
		$tb_trser_market_mail .= __('Size: ','tb_trser_market') . ($_FILES["tb_trser_file"]["size"] / 1024) . " Kb\n";
		//$tb_trser_market_message .= "Temp file: " . $_FILES["tb_trser_file"]["tmp_name"] . "<br />";
		$tb_trser_market_mail .= __('Temp file: ','tb_trser_market') . $_FILES["tb_trser_file"]["tmp_name"] . "\n";
		
		if (file_exists(content_url()."/uploads/orders/" . $_FILES["tb_trser_file"]["name"])) {
			$tb_trser_market_message .= $_FILES["tb_trser_file"]["name"] . __(' already exists. ','tb_trser_market');
			$tb_trser_market_mail .= $_FILES["tb_trser_file"]["name"] . " already exists. ";
		}
		else{
			$upload = wp_upload_bits(uniqid()._.$_FILES["tb_trser_file"]["name"], null, file_get_contents($_FILES["tb_trser_file"]["tmp_name"]));
			//$tb_trser_market_message .= "File location: " . $upload['file'] . "<br />";
			$tb_trser_market_mail .= "File location: " . $upload['file'] . "\n";
			//$tb_trser_market_message .= "Url: " . $upload['url'] . "<br />";
			$tb_trser_market_mail .= "Url: " . $upload['url'] . "\n";
			if($upload['error'])
			{
				$tb_trser_market_message .= __('Errors generated: ','tb_trser_market') . $upload['error'] . "<br />";
				$tb_trser_market_mail .= "Errors generated: " . $upload['error'] . "\n";
			}
			else
			{
				$tb_trser_market_message .= __('File uploaded succesfully!','tb_trser_market')."<br />";
				$tb_trser_market_mail .= "File uploaded succesfully! \n";
				$parse_array = array ( "tb_trser_market_document_link" => $upload['url'],
  								       "tb_trser_market_document_path" => $upload['file'],
									   "tb_trser_market_document_name" => $_FILES["tb_trser_file"]["name"],
									   "tb_trser_market_importance" => $_POST["tb_trser_market_importance"]);
				$tb_trser_market_message .= __('Order id: ','tb_trser_market') .$_POST["tb_trser_market_order_id"]."<br />";
				$tb_trser_market_message .= __('Layout importance: ','tb_trser_market') .$_POST["tb_trser_market_importance"]."<br />";
				if(isset($_POST["tb_trser_market_order_id"])){
					// translation is ready 
					// send mail to announce the new introduction of the file 
					$tb_trser_market_message .=  __('A new translation has been submitted for quotation via linguisticguide.com!','tb_trser_market')."<br />";
					$tb_trser_market_mail .= "A new translation has been submitted for quotation via linguisticguide.com!\n";
					// add the order id to sucessfully enter it in the database
					$parse_array['tb_trser_market_order_id'] = $_POST["tb_trser_market_order_id"];
					tb_trser_market_set_user_translation($parse_array);
					global $current_user;
					$tb_trser_market_mail .= "Upload by: ".$current_user->user_login."\n";
					$tb_trser_market_mail .= "Uploader email : ".$current_user->user_email."\n";
					$tb_trser_market_mail .= "Customer email : ".tb_trser_market_get_user_email($_POST["tb_trser_market_order_id"])."\n";
					wp_mail("contact@linguisticguide.com", 'A new file has been finished!', $tb_trser_market_mail);
					// include the location of the mail text
					require_once('includes/tb_trser_market_notification_emails.php');
					// place the mail text
					$tb_trser_market_customer_mail = tb_trser_market_customer_mail_file_translated($upload['url']);
					wp_mail(tb_trser_market_get_user_email($_POST["tb_trser_market_order_id"]), __('[Linguistic guide] Your file ','tb_trser_market').$_FILES["tb_trser_file"]["name"].__(' has been translated','tb_trser_market'), $tb_trser_market_customer_mail);
				}else{
					// new entry for an order 
					// send mail to announce the new introduction of the file 
					$tb_trser_market_mail .= "A new file has been submitted for quotation via linguisticguide.com!\n";
					$tb_trser_market_message .=  __('A new file has been submitted for quotation via linguisticguide.com!','tb_trser_market')."<br />";
					tb_trser_market_set_user_order($parse_array);
					global $current_user;
					$tb_trser_market_mail .= "Upload by: ".$current_user->user_login."\n";
					$tb_trser_market_mail .= "Email : ".$current_user->user_email."\n";
					wp_mail("contact@linguisticguide.com", 'A new file has been submitted for translation', $tb_trser_market_mail);

				}
			}
		}
	}
}
else
{
	$tb_trser_market_message .= __('For security reasons, please upload only files with the following extensions: xls, xlsx, doc, docx, .pdf. For other types of files, please contact us via e-mail: contact@linguisticguide.com.','tb_trser_market');
}
// Redirect the page to the configuration form that was
// processed
tb_trser_market_transfer_message($tb_trser_market_message);

wp_redirect( add_query_arg( array('page' => 'tbtranslationservicesmarketplace/tbtranslationservicesmarketplace.php',
								  'message' => '1'),
								  admin_url( 'admin.php' ) ) );
exit;
}
/* parsing global messages */
function tb_trser_market_transfer_message($message){
	if($message!=false)
	{
		/* there is a new message add it to the database */
		if ( get_option( 'tb_trser_market_message' ) === false ) {
			$new_options['tb_trser_market_message_orders'] = $message;
			add_option( 'tb_trser_market_message', $new_options );
		} else {
			$new_options['tb_trser_market_message_orders'] = $message;
			update_option( 'tb_trser_market_message', $new_options );
		}
		
	}
	else{
		if ( get_option( 'tb_trser_market_message' ) === false ) {
			/* if there is no message create it */
			$new_options['tb_trser_market_message_orders'] = __('No message present!','tb_trser_market');
			add_option( 'tb_trser_market_message', $new_options );
		} else {
			/* just retrive the message */
			$existing_options = get_option( 'tb_trser_market_message' );
			$message = $existing_options['tb_trser_market_message_orders'];
		}
	}
	return $message;
}


// funtion to present all the states the are present for one file
function tb_trser_market_dummy_translation(){
	__('finished','tb_trser_market');
	__('new','tb_trser_market');
	__('canceled','tb_trser_market');
	__('quoted','tb_trser_market');
	__('accepted','tb_trser_market');
	__('not quoted','tb_trser_market');
	__('very important','tb_trser_market');
	__('less important','tb_trser_market');
	__('not important','tb_trser_market');
}
?>